<template>
  <view class="wrap" :style="colorStyle">
    <view class="container">
      <view class="tab_box flex_s">
        <view
          class="tab_item"
          :class="{ active: current == item.id }"
          v-for="(item, index) in tabList"
          :key="index"
          @click="changTab(item.id)"
        >
          {{ item.name }}
        </view>
      </view>
      <view class="input_box">
        <view class="list" v-if="current !== 1">
          <form @submit.prevent="submit">
            <view class="item">
              <view class="flex_s row_middle">
                <view class="lable">账号</view>
                <input
                  type="number"
                  placeholder="输入手机号"
                  v-model="account"
                  maxlength="11"
                  required
                />
              </view>
            </view>
            <!-- 解决ios键盘闪烁的问题 -->
            <input type="text" style="height: 0; min-height: 0" />
            <view class="item">
              <view class="flex_s row_middle">
                <view class="lable">密码</view>
                <input
                  :type="eye ? 'text' : 'password'"
                  placeholder="填写登录密码"
                  v-model="password"
                  required
                />
                <text
                  :class="
                    eye
                      ? 'iconfont icon-yanjing_kai'
                      : 'iconfont icon-yanjing_bi'
                  "
                  @click="changeEye"
                ></text>
              </view>
            </view>
          </form>
        </view>
        <view class="list" v-if="current !== 0">
          <view class="item">
            <view class="flex_s row_middle">
              <view class="lable">账号</view>
              <input
                type="number"
                placeholder="输入手机号"
                v-model="account"
                :maxlength="11"
              />
            </view>
          </view>
          <view class="item">
            <view class="flex_s row_middle">
              <view class="lable">验证码</view>
              <input
                type="text"
                placeholder="填写验证码"
                :maxlength="6"
                class="codeIput"
                v-model="captcha"
              />
              <button
                class="code"
                :disabled="disabled"
                :class="disabled === true ? 'on' : ''"
                @click="code"
              >
                {{ text }}
              </button>
            </view>
          </view>
        </view>
        <!-- 验证码登录 -->
        <view class="logon" @click="codeLoginDebounce" v-if="current !== 0">
          登录
        </view>
        <!-- 账号密码登录 -->
        <view class="logon" @click="submitDebounce" v-if="current === 0">
          登录
        </view>
      </view>
      <view class="footer flex_c">
        <navigator
          class="foot_item"
          hover-class="none"
          url="/pages/users/register"
        >
          注册账号
        </navigator>
        <text class="line">|</text>
        <navigator
          class="foot_item"
          hover-class="none"
          url="/pages/users/forget"
        >
          忘记密码
        </navigator>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { useTheme } from "@/composables/useTheme";
import { Tips } from "@/utils";
import { login, getUserInfo, codeLogin, sendsms } from "@/api/user";
import { useSendCode } from "@/composables/useSendCode";
import { useBusinTokenStore } from "@/store";
import saveUserInfoToLocation from "@/composables/saveUserInfoToLocation";
import { debounceImmediate } from "@/utils/validate";
import themeList from "@/utils/theme";
import { onLoad, onReady, onShow } from "@dcloudio/uni-app";
import { hidePageNavInWechatBrowser } from "@/composables/useHiddenNavbar";
import { getWechatFollow } from "@/api/user";
import Cache from "@/utils/cache";
import { USER_INFO, LOGIN_STATUS } from "@/config/cache";
// import hideWechatMenu from "@/composables/hideWechatMenu";
onShow(() => {
  // if (Cache.get(LOGIN_STATUS)) getWechatFollowHanlder();
  // hideWechatMenu();
});
onReady(() => {
  hidePageNavInWechatBrowser();
});
// 我的提醒列表(判断微信授权登录状态是否过期，从而自动跳转入口页面授权)
function getWechatFollowHanlder() {
  getWechatFollow();
}
const { disabled, text, sendCode } = useSendCode();
const { colorStyle } = useTheme();

let eye = ref(false);
function changeEye() {
  eye.value = !eye.value;
}
let tabList = ref([
  {
    name: "账号密码",
    id: 0,
  },
  {
    name: "验证登录",
    id: 1,
  },
]);
let account = ref("");
let password = ref("");
let captcha = ref("");
let current = ref(0);
function changTab(id: number) {
  current.value = id;
}
const submitDebounce = debounceImmediate(submit, 500);
async function submit() {
  if (!account.value)
    return Tips({
      title: `请填写账号`,
    });
  // if (!/^[\w\d]{5,16}$/i.test(account.value))
  //   return Tips({
  //     title: `请输入正确的账号`,
  //   });
  if (!password.value)
    return Tips({
      title: `请填写密码`,
    });
  try {
    const res: any = await login({
      phone: account.value,
      password: password.value,
    });

    console.log(res, "登录成功");
    const data = res.data;
    const token = data.busion_token.token;

    Tips({
      title: res.info,
    });

    // 确保 token 设置完成后再继续执行
    const tokenStore = useBusinTokenStore();
    await tokenStore.setToken(token);

    // 等待一小段时间确保持久化完成（可选）
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 获取用户信息
    try {
      const userInfoRes: any = await getUserInfo();
      const userInfoData = userInfoRes.data.business;

      // 存储用户信息
      saveUserInfoToLocation(userInfoData);

      uni.reLaunch({
        url: "/pages/tabbar/home",
        fail(err) {
          console.log(err, "跳转错误");
        },
      });
    } catch (error) {
      console.log(error, "获取用户信息失败");
    }
  } catch (res: any) {
    Tips({
      title: res.info,
    });
  }
}
const codeLoginDebounce = debounceImmediate(codeLoginHandler, 500);
async function codeLoginHandler() {
  if (!account.value) {
    return Tips({
      title: `请填写账号`,
    });
  }

  if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(account.value)) {
    return Tips({
      title: `请输入正确的账号`,
    });
  }

  if (!captcha.value) {
    return Tips({
      title: `请填写验证码`,
    });
  }

  if (!/^[\w\d]+$/i.test(captcha.value)) {
    return Tips({
      title: `请输入正确的验证码`,
    });
  }

  codeLogin({
    phone: account.value,
    verify: captcha.value,
    // spread: that.$Cache.get('spread')
  })
    .then(async (res) => {
      const data = res.data;
      const token = data.busion_token.token;
      Tips({
        title: res.info,
      });
      // 确保 token 设置完成后再继续执行
      const tokenStore = useBusinTokenStore();
      await tokenStore.setToken(token);

      // 等待一小段时间确保持久化完成（可选）
      await new Promise((resolve) => setTimeout(resolve, 500));

      // 获取用户信息
      try {
        const userInfoRes: any = await getUserInfo();
        const userInfoData = userInfoRes.data.business;
        // 存储用户信息
        saveUserInfoToLocation(userInfoData);
        uni.reLaunch({
          url: "/pages/tabbar/home",
          fail(err) {
            console.log(err, "跳转错误");
          },
        });
      } catch (error) {
        console.log(error, "获取用户信息失败");
      }
    })
    .catch((res) => {
      console.log(res, "报差错");
      Tips({
        title: res.info,
      });
    });
}
// 设置主题样式
function setThemeHandler(themeValue, subThemeValue) {
  // 合并默认主题
  const mergedTheme =
    themeList["theme"][themeValue] + themeList["sub_theme"][subThemeValue];
  uni.setStorageSync("viewColor", mergedTheme);
}
// 获取验证码
async function code() {
  if (!account.value)
    return Tips({
      title: `请填写账号`,
    });
  if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(account.value))
    return Tips({
      title: `请输入正确的账号`,
    });
  if (!disabled.value) {
    uni.showLoading();
    let codeData = await getCodeHandler();
    if (codeData.code == 1) {
      uni.showToast({
        title: codeData.info,
      });
    } else {
      return;
    }
  }
  sendCode();
}
function getCodeHandler() {
  const params = {
    is_type: 3,
    phone: account.value,
  };
  console.log(params);

  return sendsms(params);
}
</script>

<style scoped lang="scss">
.wrap {
  min-height: 100vh;
  background: linear-gradient(
    175.6deg,
    rgba(205, 212, 215, 0) 6%,
    rgba(207, 214, 217, 1) 96%
  );
  padding-top: 450rpx;
  background-image: url("/static/image/login1.png");
  background-repeat: no-repeat;
  background-size: 100% auto;

  .container {
    padding: 0 70rpx;
    .footer {
      color: #3b3630;
      margin-top: 100rpx;
      .foot_item {
        font-size: 30rpx;
      }
      .line {
        margin: 0 30rpx;
      }
    }
    .input_box {
      padding: 0 30rpx;
      .list {
        border-radius: 16rpx;
        overflow: hidden;

        .item {
          border-bottom: 1px solid #e8e8e8;
          // background: #f6f8fa;
          margin-bottom: 20rpx;
          // border-radius: 14rpx;
          .row_middle {
            position: relative;
            // padding: 16rpx 45rpx;
            .iconfont {
              font-size: 30rpx;
              color: #000;
            }
            .lable {
              font-size: 30rpx;
              color: #3b3630;
              min-width: 130rpx;
            }
            input {
              flex: 1;
              font-size: 28rpx;
              height: 80rpx;
            }

            .code {
              z-index: 100;
              position: absolute;
              right: 0;
              top: 50%;
              color: #0d81d3;
              font-size: 30rpx;
              transform: translateY(-50%);
            }
          }
        }
      }
    }
  }
  .tab_box {
    height: 90rpx;
    margin-bottom: 30rpx;

    .tab_item {
      padding: 0 20rpx;
      font-size: 34rpx;
      color: #3b3630;
      height: 100%;
      text-align: center;
      line-height: 100rpx;
      margin-right: 30rpx;
    }
    .active {
      font-weight: bold;
      color: #3b3630;
      position: relative;
      font-size: 35rpx;
      &::before {
        content: "";
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 50%;
        height: 4rpx;
        background: var(--view-theme);
      }
    }
  }
}
</style>
